package com.ia.bikerecife.twitter;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import com.ia.bikerecife.core.ProgramD;
import com.ia.bikerecife.database.Banco;

import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterResponder extends TimerTask {
	
	ConfigurationBuilder cb;
	Twitter twitter;
	List<Status> statuses = new ArrayList<Status>();
	List<Long> IdAlready =  new ArrayList<Long>();
	
	String InputTexto = new String("");
	String OutputTexto = new String("");
	String ConsultaBanco = new String("");
	
	ProgramD agente = new ProgramD();
	
	public TwitterResponder(){ 
		cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true)
		  .setOAuthConsumerKey("GPOdJmhYDp4pUjUD9DQ")
		  .setOAuthConsumerSecret("FA0xvntzMbd2V5eu9eTc6RrlAXEKScNdYHpAdlKmic")
		  .setOAuthAccessToken("2167694672-Xu2OtTyegpNBNVW0gUFkVekJ3niVBYI1YmLi1it")
		  .setOAuthAccessTokenSecret("6vFOgq8yHM72WBMLow4DxXFv1m6ETaybE4QzA0rUw0iyG");
		twitter = new TwitterFactory(cb.build()).getInstance();
	}
	
	public void run() {
			try {
				statuses = twitter.getHomeTimeline();
			} catch (TwitterException e) {
				e.printStackTrace();
			}
			
		    for (Status status : statuses) {
		    	
		    	if(status.getUser().getName().compareTo("Marcos Canejo") < 0 && status.getText().contains("@marcoscanejo")){
		    		String arroba = new String("@"+status.getUser().getScreenName());
		    		
		    		InputTexto = status.getText().replace("@marcoscanejo", "");
		    		
		    		if(!IdAlready.contains(status.getId())){
			    		System.out.println(InputTexto);
			    		IdAlready.add(status.getId());
			    		OutputTexto = agente.askMe("@"+InputTexto).replace("#arroba#", arroba);
			    			
			    		System.out.println(OutputTexto);
			    		
			    		if(OutputTexto.contains("#banco#")){
			    			try {
								Banco banco = new Banco();
								ConsultaBanco = OutputTexto;
								System.out.println(ConsultaBanco.replace("#banco#", ""));
								OutputTexto = banco.consultar(ConsultaBanco);
								postar(OutputTexto.concat(" "+arroba));
								
							} catch (Exception e) {
								e.printStackTrace();
							}		    		
			    		}else{
				    		try {
								postar(OutputTexto);
							} catch (TwitterException e) {
								e.printStackTrace();
							}
			    		}
			    		
		    		}else{
		    			System.out.println(status.getId() + " " + InputTexto + " Msg j� respondida");
		    		}
		    	}
		    }
		    
		    System.out.println("");
    }
	
	private void postar(String mensagem) throws TwitterException{
		StatusUpdate postarMsg = new StatusUpdate(mensagem);
		twitter.updateStatus(postarMsg);
	}
}
